package net.xdclass.interceptor;

import feign.Request;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.enums.BizCodeEnum;
import net.xdclass.model.LoginUser;
import net.xdclass.util.CommonUtil;
import net.xdclass.util.JWTUtil;
import net.xdclass.util.JsonData;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class LoginInterceptor implements HandlerInterceptor{

	public static ThreadLocal<LoginUser>threadLocal = new ThreadLocal();

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		if (HttpMethod.OPTIONS.toString().equalsIgnoreCase(request.getMethod())) {
			response.setStatus(HttpStatus.NO_CONTENT.value());
			return true;
		}
		String token = request.getHeader("token");
		if (StringUtils.isBlank(token)){
			token = request.getParameter("token");
		}
		if(StringUtils.isNotBlank(token)){
		Claims claims = JWTUtil.checkJWT(token);
		if(claims == null){
			CommonUtil.sendJsonMessage(response, JsonData.buildResult(BizCodeEnum.ACCOUNT_UNLOGIN));
			return false ;
		}
		long accountNo = Long.parseLong(claims.get("accountNo").toString());
		String 	headImg = (String) claims.get("headImg");
		String 	mail = (String) claims.get("mail");
		String 	username = (String) claims.get("username");
		String 	auth = (String) claims.get("auth");
		String 	phone = (String) claims.get("phone");
        LoginUser loginUser = LoginUser.builder().accountNo(accountNo).auth(auth).mail(mail).
				phone(phone).headImg(headImg).username(username).build();
      //  request.setAttribute("loginUser",loginUser);
         log.info("loginUser",loginUser.toString());
		threadLocal.set(loginUser);
		log.info("loginUser",threadLocal.get().toString());
		return true; }
		return false;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		threadLocal.remove();
	}
}
